How do I delete a [sub]hash based off of the keys/values of another hash?
Posted
by Zack
on Stack Overflow
See other posts from Stack Overflow
or by Zack
Published on 2010-04-02T20:41:19Z
Indexed on
2010/04/02
20:43 UTC
Read the original article
Hit count: 294
Lets assume I have two hashes. One of them contains a set of data that only needs to keep things that show up in the other hash.
e.g.
my %hash1 = (
test1 => { inner1 => { more => "alpha", evenmore => "beta" } },
test2 => { inner2 => { more => "charlie", somethingelse => "delta" } },
test3 => { inner9999 => { ohlookmore => "golf", somethingelse => "foxtrot" } }
);
my %hash2 = (
major=> { test2 => "inner2",
test3 => "inner3" } );
What I would like to do, is to delete the whole subhash in hash1 if it does not exist as a key/value in hash2{major}, preferably without modules. The information contained in "innerX" does not matter, it merely must be left alone (unless the subhash is to be deleted then it can go away).
In the example above after this operation is preformed hash1 would look like:
my %hash1 = (
test2 => { inner2 => { more => "charlie", somethingelse => "delta" } },
);
It deletes hash1{test1} and hash1{test3} because they don't match anything in hash2.
Here's what I've currently tried, but it doesn't work. Nor is it probably the safest thing to do since I'm looping over the hash while trying to delete from it. However I'm deleting at the each which should be okay?
This was my attempt at doing this, however perl complains about:
Can't use string ("inner1") as a HASH ref while "strict refs" in use at
while(my ($test, $inner) = each %hash1)
{
if(exists $hash2{major}{$test}{$inner})
{
print "$test($inner) is in exists.\n";
}
else
{
print "Looks like $test($inner) does not exist, REMOVING.\n";
#not to sure if $inner is needed to remove the whole entry
delete ($hash1{$test}{$inner});
}
}
© Stack Overflow or respective owner